package com.mlog.njyjy.ndop.monitor.collector.service.impl;

import cn.hutool.core.util.StrUtil;
import com.mlog.njyjy.ndop.monitor.collector.dao.TaskRepository;
import com.mlog.njyjy.ndop.monitor.collector.service.ProductMonitorService;
import com.mlog.njyjy.ndop.monitor.collector.service.TaskService;
import com.mlog.njyjy.ndop.monitor.common.domain.Task;
import com.mlog.njyjy.ndop.monitor.common.utils.DateTimeUtil;
import com.mlog.njyjy.ndop.share.sql.support.SqlTableUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 监控任务service
 *
 * @author zyz
 * @version v1.0, 2020/07/24
 */
@Slf4j
@Service
public class TaskServiceImpl implements TaskService {

    @Autowired
    private TaskRepository repository;

    @Autowired
    private ProductMonitorService productMonitorService;

    @Override
    public List<Task> findAll() {
        return repository.findAll();
    }

    @Override
    public Task findOne(int id) {
        return repository.findOne(id);
    }

    @Override
    public boolean save(Task task) {
        boolean succeed;
        if (task.getId() == 0) {
            succeed = repository.insert(task);
        } else {
            succeed = repository.update(task);
        }
        if (succeed) {
            //加入定时任务
            Task existed = repository.findFirst(StrUtil.format("select * from {} where product_name = '{}' and start_proc_at = '{}'",
                    SqlTableUtil.getTblName(Task.class), task.getProductName(), DateTimeUtil.formatDefault(task.getStartProcAt())));
            productMonitorService.addTask(existed);
        }
        return succeed;
    }

    @Override
    public boolean delete(int id) {
        boolean succeed = repository.delete(id);
        if (succeed) {
            //移除定时任务
            productMonitorService.removeTask(id);
        }
        return succeed;
    }


}
